package com.wyutil.wy_FileFormatConversion.ImageWithExcel;

import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

public class ExcelToImage {
    public void excel2Pic(InputStream fileInputStream, String targetPicPath) {
        Workbook wb = new Workbook();
        wb.loadFromStream(fileInputStream);
        Worksheet sheet = wb.getWorksheets().get(0);
        //调用方法将Excel工作表保存为图片
        sheet.saveToImage(targetPicPath);
    }

    /**
     * excel转 图片 使用默认值
     * @return
     * @throws IOException
     */
    public ByteArrayOutputStream excel2Pic(InputStream sourceFileInputStream) throws IOException {
        return excel2Pic(sourceFileInputStream, FileType.ImageType.PNG, 0);
    }
    /**
     * excel 转图片  多个参数
     * @param fileInputStream
     * @param imageType
     * @param sheetNum
     * @return
     * @throws IOException
     */
    public ByteArrayOutputStream excel2Pic(InputStream fileInputStream,  FileType.ImageType imageType, int sheetNum) throws IOException {
        Workbook wb = new Workbook();
        wb.loadFromStream(fileInputStream);
        //获取工作表
        Worksheet sheet = wb.getWorksheets().get(sheetNum);
        //调用方法将Excel工作表保存为图片
        BufferedImage bufferedImage = sheet.toImage(1, 1, sheet.getLastRow(), sheet.getLastColumn());
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, imageType.name(), byteArrayOutputStream);
        return byteArrayOutputStream;
    }

    public static void main(String[] args) throws IOException {
        ExcelToImage excelToImage = new ExcelToImage();
        FileInputStream fileInputStream = new FileInputStream("C:\\Users\\wy\\Downloads\\2222.xls");
        ByteArrayOutputStream byteArrayOutputStream = excelToImage.excel2Pic(fileInputStream, FileType.ImageType.JPG, 0);
        FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\wy\\Downloads\\2222.jpg");
        fileOutputStream.write(byteArrayOutputStream.toByteArray());
    }
}
